import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time,sys
import plugin_helper

class KofikoManager:
  
  def __init__(self):
    self.MODES=plugin_helper.enum(GET_SERIES_LIST=1,GET_EPISODES_LIST=2,PLAY=3)
  
  def work(self,mode,url='',name=''):
    if (mode==self.MODES.GET_SERIES_LIST):
      self.getSeriesList()
    elif(mode==self.MODES.GET_EPISODES_LIST):
      self.getEpisodeList(url,name)
    elif(mode==self.MODES.PLAY):
      plugin_helper.playRtmpFromUrl(url)
      
  def getSeriesList(self):
    types=[('1720884','חוקי הג\'ונגל'),('1717717','סיפור לגיל הרך'),('1717716','קריוקי עם קופיקו'),('1717740','פרקים מלאים (עונה 1)')]
    for url,name in types:
      plugin_helper.addDir('Kofiko',name,url,2,{"Title": urllib.unquote(name)})
    xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
    
  def getEpisodeList(self,url,name):
    matches = self.getFromAjax('http://video.walla.co.il/?w=//'+url)
    for url,img,title in matches:
      plugin_helper.addVideo('Kofiko',title,'','http://kofiko.walla.co.il/?w=//'+url,3,{'Title':title},img)
  
  def getFromAjax(self,url):
    print(url)
    match=[]
    length = 1
    i=0
    url = url + '&page='
    while (length>0 and i<=10):
      pat='location\.href=&quot;\?w=//(\d+)&quot;"><span class="block relative zoom1"><img class="absolute zoomImg" style="top:30px;left:68px;" src="http://iscWBE.walla.co.il/w9/v/vod/PLAYBTN_white.gif" alt="" /></span><img class="vmedia141x78 medhvr01" src="(.*?)" alt="(.*?)" />'
      news = plugin_helper.getMatches(url+str(i),pat)
      length=len(news)
      match+=news
      i+=1
    return match
